<template>
  <PageLayout
    title="角色管理"
    subtitle="管理系统用户角色"
    icon="fa fa-user-tag"
    class="apply-glass-theme"
  >
    <template #toolbar-left>
      <el-button type="primary" @click="showCreateDialog" class="tech-button">
        <i class="fa fa-plus"></i> 新增角色
      </el-button>
      <el-button @click="refreshRoles" class="tech-button">
        <i class="fa fa-refresh"></i> 刷新
      </el-button>
    </template>

    <template #toolbar-right>
      <el-input
        v-model="searchText"
        placeholder="搜索角色名称或描述..."
        clearable
        class="tech-input"
        style="width: 350px"
      >
        <template #prefix>
          <i class="fa fa-search"></i>
        </template>
      </el-input>
    </template>

    <template #content>
      <div class="glass-card">
        <el-table
          :data="filteredRoles"
          v-loading="loading"
          class="glass-dialog tech-table"
          stripe
          border
          height="calc(100vh - 380px)"
          style="width: 100%;"
          table-layout="fixed"
        >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="角色类型" width="120">
          <template #default="{ row }">
            <el-tag :type="row.is_system ? 'warning' : 'info'">
              {{ row.is_system ? '系统角色' : '自定义角色' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="权限数量" width="120">
          <template #default="{ row }">
            <el-tag type="success">{{ row.permission_count || 0 }} 个</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="关联用户组" width="250">
          <template #default="{ row }">
            <div v-if="row.groups && row.groups.length > 0">
              <!-- 如果只有1-2个用户组，直接显示 -->
              <div v-if="row.groups.length <= 2" class="single-groups">
                <el-tag
                  v-for="group in row.groups"
                  :key="group.id"
                  size="small"
                  type="info"
                  style="margin-right: 4px; margin-bottom: 2px;"
                >
                  {{ group.name }}
                </el-tag>
              </div>
              <!-- 如果有多个用户组，整个区域都可以悬浮 -->
              <el-popover
                v-else
                placement="top"
                width="400"
                trigger="hover"
                popper-class="host-group-popover"
              >
                <template #reference>
                  <div class="groups-container">
                    <el-tag
                      v-for="group in row.groups.slice(0, 2)"
                      :key="group.id"
                      size="small"
                      type="info"
                      style="margin-right: 4px; margin-bottom: 2px;"
                    >
                      {{ group.name }}
                    </el-tag>
                    <el-tag
                      size="small"
                      type="warning"
                      style="margin-left: 4px;"
                    >
                      共{{ row.groups.length }}个组
                    </el-tag>
                  </div>
                </template>
                <div class="group-detail">
                  <h4 style="color: #00eaff; margin: 0 0 12px 0;">{{ row.name }} - 关联用户组</h4>
                  <div class="group-list">
                    <el-tag
                      v-for="group in row.groups"
                      :key="group.id"
                      size="small"
                      type="info"
                      style="margin-right: 6px; margin-bottom: 6px;"
                    >
                      {{ group.name }}
                    </el-tag>
                  </div>
                  <div style="margin-top: 8px; font-size: 12px; color: rgba(255,255,255,0.7);">
                    总计：{{ row.groups.length }} 个用户组
                  </div>
                </div>
              </el-popover>
            </div>
            <span v-else class="text-muted">未关联</span>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="320" fixed="right" align="center">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                size="small"
                type="primary"
                @click="editRole(row)"
                class="action-btn glass-button"
              >
                <i class="fa fa-edit"></i> 编辑
              </el-button>
              <el-button
                size="small"
                type="info"
                @click="managePermissions(row)"
                class="action-btn glass-button"
              >
                <i class="fa fa-key"></i> 权限
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="deleteRole(row)"
                class="action-btn glass-button"
              >
                <i class="fa fa-trash"></i> 删除
              </el-button>
            </div>
          </template>
        </el-table-column>
        </el-table>
      </div>
    </template>

    <template #dialogs>
      <!-- 创建/编辑角色对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="650px"
        class="tech-dialog"
      >
        <el-form :model="roleForm" :rules="roleRules" ref="roleFormRef" label-width="100px" class="tech-form">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="角色名" prop="name">
                <el-input v-model="roleForm.name" placeholder="请输入角色名称" class="tech-input" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="描述" prop="description">
                <el-input v-model="roleForm.description" type="textarea" :rows="3" placeholder="请输入角色描述" class="tech-input" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false" class="tech-button">取消</el-button>
            <el-button type="primary" @click="saveRole" class="tech-button">
              {{ isEdit ? '更新' : '创建' }}
            </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 权限管理对话框 -->
      <el-dialog
        v-model="permissionsDialogVisible"
        title="管理角色权限"
        width="800px"
        class="tech-dialog"
      >
        <div class="permissions-management">
          <div class="permissions-section">
            <h4>菜单权限</h4>
            <el-tree
              ref="permissionTreeRef"
              :data="menuTreeData"
              node-key="id"
              show-checkbox
              :props="{ label: 'label', children: 'children' }"
              :default-checked-keys="[]"
              @check="handlePermissionChange"
              class="permission-tree"
            >
              <template #default="{ node, data }">
                <div class="tree-node-wrapper">
                  <div class="menu-node">
                    <div class="menu-info">
                      <i :class="data.icon || 'fa fa-folder'" class="menu-icon"></i>
                      <div class="menu-details">
                        <span class="menu-name">{{ data.name }}</span>
                        <span class="menu-path" v-if="data.path">{{ data.path }}</span>
                      </div>
                    </div>
                    <!-- 权限控制内联显示 -->
                    <div class="permission-controls-inline" v-if="node.checked">
                      <el-tag
                        :type="getPermissionTagType(data.id)"
                        size="small"
                        class="permission-status-tag"
                      >
                        {{ getPermissionText(data.id) }}
                      </el-tag>
                      <div class="permission-button-group">
                        <el-button
                          :type="isReadOnlyPermission(data.id) ? 'primary' : ''"
                          :class="{ 'active-permission': isReadOnlyPermission(data.id) }"
                          @click.stop="setPermissionLevel(data.id, 'read')"
                          size="small"
                          class="permission-control-btn"
                        >
                          <i class="fa fa-eye"></i> 只读
                        </el-button>
                        <el-button
                          :type="isReadWritePermission(data.id) ? 'primary' : ''"
                          :class="{ 'active-permission': isReadWritePermission(data.id) }"
                          @click.stop="setPermissionLevel(data.id, 'write')"
                          size="small"
                          class="permission-control-btn"
                        >
                          <i class="fa fa-edit"></i> 读写
                        </el-button>
                      </div>
                    </div>
                  </div>
                </div>
              </template>
            </el-tree>
          </div>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="permissionsDialogVisible = false" class="tech-button">取消</el-button>
            <el-button type="primary" @click="savePermissions" class="tech-button">保存权限</el-button>
          </div>
        </template>
      </el-dialog>
    </template>
  </PageLayout>
</template>

<script setup lang="ts">
import PageLayout from '@/components/PageLayout.vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, nextTick, onMounted, ref } from 'vue'
import { STATIC_MENUS } from '@/config/menus'

// 响应式数据
const loading = ref(false)
const roles = ref([])
const menus = ref([])
const searchText = ref('')
const dialogVisible = ref(false)
const permissionsDialogVisible = ref(false)
const isEdit = ref(false)
const roleFormRef = ref()
const permissionTreeRef = ref()
const currentRole = ref(null)
const checkedPermissions = ref([])
const menuPermissions = ref({})

// 角色表单
const roleForm = ref({
  id: null,
  name: '',
  description: ''
})

// 表单验证规则
const roleRules = {
  name: [
    { required: true, message: '请输入角色名', trigger: 'blur' },
    { min: 2, max: 50, message: '角色名长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑角色' : '新增角色')
const filteredRoles = computed(() => {
  if (!searchText.value) return roles.value
  return roles.value.filter((role: any) =>
    role.name.toLowerCase().includes(searchText.value.toLowerCase()) ||
    (role.description && role.description.toLowerCase().includes(searchText.value.toLowerCase()))
  )
})

const menuTreeData = computed(() => {
  return buildMenuTree(menus.value)
})

// 方法
const fetchRoles = async () => {
  loading.value = true
  try {
    const response = await axios.get('/api/roles/')
    roles.value = response.data.results || response.data
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}



const fetchMenus = async () => {
  try {
    // 使用前端静态菜单配置，确保数据一致性
    console.log('📋 角色管理 - 使用静态菜单配置，菜单数量:', STATIC_MENUS.length)
    menus.value = STATIC_MENUS
  } catch (error) {
    console.error('获取菜单列表失败:', error)
    // 如果出错，使用静态菜单作为备用
    menus.value = STATIC_MENUS
  }
}

const refreshRoles = () => {
  fetchRoles()
}

const showCreateDialog = () => {
  isEdit.value = false
  roleForm.value = {
    id: null,
    name: '',
    description: ''
  }
  dialogVisible.value = true
}

const editRole = (role: any) => {
  isEdit.value = true
  roleForm.value = {
    id: role.id,
    name: role.name,
    description: role.description || ''
  }
  dialogVisible.value = true
}

const saveRole = async () => {
  try {
    await roleFormRef.value.validate()

    if (isEdit.value) {
      await axios.put(`/api/roles/${roleForm.value.id}/`, roleForm.value)
      ElMessage.success('角色更新成功')
    } else {
      await axios.post('/api/roles/', roleForm.value)
      ElMessage.success('角色创建成功')
    }

    dialogVisible.value = false
    fetchRoles()
  } catch (error) {
    console.error('保存角色失败:', error)
    ElMessage.error('保存角色失败')
  }
}

const deleteRole = async (role: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这个角色吗？', '确认删除', {
      type: 'warning'
    })

    await axios.delete(`/api/roles/${role.id}/`)
    ElMessage.success('角色删除成功')
    fetchRoles()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除角色失败:', error)
      ElMessage.error('删除角色失败')
    }
  }
}

const managePermissions = async (role: any) => {
  currentRole.value = role

  // 重置状态
  checkedPermissions.value = []
  menuPermissions.value = {}

  try {
    const response = await axios.get(`/api/roles/${role.id}/permissions/`)
    const permissions = response.data

    console.log('角色权限数据:', permissions)

    // 将路径映射到菜单ID的函数
    const findMenuIdByPath = (menuList: any[], targetPath: string): string | null => {
      for (const menu of menuList) {
        if (menu.path === targetPath) {
          return menu.id || menu.path?.replace(/\//g, '-')
        }
        if (menu.children) {
          const found = findMenuIdByPath(menu.children, targetPath)
          if (found) return found
        }
      }
      return null
    }

    // 设置选中的菜单和权限
    permissions.forEach((perm: any) => {
      // 后端返回的数据中，menu_path是路径，menu_item是数字ID
      const menuPath = perm.menu_path || perm.menu_item  // 优先使用menu_path
      const menuId = findMenuIdByPath(menus.value, menuPath)

      console.log(`📋 角色管理 - 权限映射: ${menuPath} -> ${menuId}`)
      console.log(`📋 角色管理 - 权限数据:`, perm)

      if (menuId) {
        checkedPermissions.value.push(menuId)
        menuPermissions.value[menuId] = {
          can_read: perm.can_read,
          can_write: perm.can_write
        }
      } else {
        console.warn(`⚠️  角色管理 - 无法找到菜单: ${menuPath}`)
        console.warn(`⚠️  角色管理 - 权限数据:`, perm)
      }
    })

    console.log('📋 角色管理 - 最终选中的菜单IDs:', checkedPermissions.value)
    console.log('📋 角色管理 - 菜单权限配置:', menuPermissions.value)

    console.log('提取的菜单ID:', checkedPermissions.value)
    console.log('权限配置:', menuPermissions.value)

    permissionsDialogVisible.value = true

    // 等待DOM更新后设置选中状态
    await nextTick()

    // 延迟设置选中状态，确保菜单树完全渲染
    setTimeout(async () => {
      if (permissionTreeRef.value) {
        console.log('📋 角色管理 - 开始设置菜单选中状态:', checkedPermissions.value)

        // 先清空所有选中状态
        if (typeof permissionTreeRef.value.setCheckedKeys === 'function') {
          permissionTreeRef.value.setCheckedKeys([])
          console.log('📋 角色管理 - 清空现有选中状态')
        }

        if (checkedPermissions.value.length > 0) {
          // 先展开有选中子项的父菜单
          const expandKeys = []
          checkedPermissions.value.forEach(menuId => {
            // 查找父菜单
            const findParent = (menuList: any[], targetId: string): string | null => {
              for (const menu of menuList) {
                if (menu.children) {
                  for (const child of menu.children) {
                    if (child.id === targetId) {
                      return menu.id
                    }
                  }
                  const found = findParent(menu.children, targetId)
                  if (found) return found
                }
              }
              return null
            }

            const parentId = findParent(menus.value, menuId)
            if (parentId && !expandKeys.includes(parentId)) {
              expandKeys.push(parentId)
            }
          })

          // 设置展开状态
          if (expandKeys.length > 0) {
            console.log('📋 角色管理 - 自动展开父菜单:', expandKeys)
          }

          // 等待展开动画完成后设置选中状态
          await nextTick()
          setTimeout(() => {
            if (permissionTreeRef.value && typeof permissionTreeRef.value.setCheckedKeys === 'function') {
              permissionTreeRef.value.setCheckedKeys(checkedPermissions.value)
              console.log('✅ 角色管理 - 菜单选中状态设置完成:', checkedPermissions.value)

              // 验证设置结果
              setTimeout(() => {
                if (typeof permissionTreeRef.value?.getCheckedKeys === 'function') {
                  const actualChecked = permissionTreeRef.value.getCheckedKeys() || []
                  console.log('📋 角色管理 - 验证选中状态:', actualChecked)
                  if (actualChecked.length !== checkedPermissions.value.length) {
                    console.warn('⚠️  角色管理 - 部分菜单选中失败')
                    console.log('📋 角色管理 - 期望选中:', checkedPermissions.value)
                    console.log('📋 角色管理 - 实际选中:', actualChecked)
                  }
                }
              }, 100)
            } else {
              console.warn('⚠️  角色管理 - setCheckedKeys 方法不存在')
            }
          }, 300)
        } else {
          console.log('📋 角色管理 - 没有需要选中的菜单')
        }
      } else {
        console.warn('⚠️  角色管理 - permissionTreeRef 不存在')
      }
    }, 500)
  } catch (error) {
    console.error('获取角色权限失败:', error)
    ElMessage.error('获取角色权限失败')
    checkedPermissions.value = []
    menuPermissions.value = {}
  }
}

const handlePermissionChange = (data: any, checked: any) => {
  // 当菜单被选中或取消选中时，初始化权限
  const checkedKeys = checked.checkedKeys

  // 为新选中的菜单设置默认权限
  checkedKeys.forEach((menuId: number) => {
    if (!menuPermissions.value[menuId]) {
      menuPermissions.value[menuId] = {
        can_read: true,
        can_write: false
      }
    }
  })

  // 移除未选中菜单的权限
  Object.keys(menuPermissions.value).forEach(menuId => {
    if (!checkedKeys.includes(parseInt(menuId))) {
      delete menuPermissions.value[menuId]
    }
  })
}

const setPermissionLevel = (menuId: number, level: 'read' | 'write') => {
  if (!menuPermissions.value[menuId]) {
    menuPermissions.value[menuId] = { can_read: true, can_write: false }
  }

  if (level === 'read') {
    menuPermissions.value[menuId].can_read = true
    menuPermissions.value[menuId].can_write = false
  } else if (level === 'write') {
    menuPermissions.value[menuId].can_read = true
    menuPermissions.value[menuId].can_write = true
  }
}

const getPermissionText = (menuId: number) => {
  const perm = menuPermissions.value[menuId]
  if (!perm || !perm.can_read) return '无权限'
  if (perm.can_read && perm.can_write) return '读写'
  if (perm.can_read && !perm.can_write) return '只读'
  return '无权限'
}

const getPermissionTagType = (menuId: number) => {
  const perm = menuPermissions.value[menuId]
  if (!perm || !perm.can_read) return 'info'
  if (perm.can_read && perm.can_write) return 'success'
  if (perm.can_read && !perm.can_write) return 'warning'
  return 'info'
}

const isReadOnlyPermission = (menuId: number) => {
  const perm = menuPermissions.value[menuId]
  return perm && perm.can_read && !perm.can_write
}

const isReadWritePermission = (menuId: number) => {
  const perm = menuPermissions.value[menuId]
  return perm && perm.can_read && perm.can_write
}

const savePermissions = async () => {
  try {
    const checkedKeys = permissionTreeRef.value?.getCheckedKeys() || []
    console.log('📋 角色管理 - 保存权限 - 选中的菜单Keys:', checkedKeys)

    // 将菜单ID映射到路径，因为后端需要路径而不是ID
    const menuPermissionsList = checkedKeys.map((menuId: string) => {
      // 查找对应的菜单项
      const findMenuByIdOrPath = (menuList: any[], targetId: string): any => {
        for (const menu of menuList) {
          if (menu.id === targetId || menu.path?.replace(/\//g, '-') === targetId) {
            return menu
          }
          if (menu.children) {
            const found = findMenuByIdOrPath(menu.children, targetId)
            if (found) return found
          }
        }
        return null
      }

      const menuItem = findMenuByIdOrPath(menus.value, menuId)
      const menuPath = menuItem?.path || menuId

      return {
        menu_id: menuPath, // 使用路径作为菜单ID
        can_read: menuPermissions.value[menuId]?.can_read || true,
        can_write: menuPermissions.value[menuId]?.can_write || false
      }
    })

    console.log('📋 角色管理 - 保存权限 - 权限列表:', menuPermissionsList)

    await axios.post(`/api/roles/${currentRole.value.id}/set_permissions/`, {
      menu_permissions: menuPermissionsList
    })
    ElMessage.success('权限保存成功')
    permissionsDialogVisible.value = false

    // 更新当前角色的权限数量
    if (currentRole.value) {
      currentRole.value.permission_count = checkedKeys.length
    }

    // 刷新角色列表
    await fetchRoles()
  } catch (error) {
    console.error('保存权限失败:', error)
    ElMessage.error('保存权限失败')
  }
}

const buildMenuTree = (menus: any[]) => {
  // 静态菜单配置已经是树形结构，直接返回
  // 但需要确保每个菜单项都有唯一的ID用于权限管理
  const processMenu = (menu: any, parentId?: string): any => {
    const processedMenu = {
      ...menu,
      // 如果没有ID，使用路径生成ID
      id: menu.id || menu.path?.replace(/\//g, '-') || Math.random().toString(36).substr(2, 9),
      label: menu.name,
      children: menu.children ? menu.children.map((child: any) => processMenu(child, menu.id)) : []
    }
    return processedMenu
  }

  return menus.map(menu => processMenu(menu))
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  fetchRoles()
  fetchMenus()
})
</script>

<style scoped>
/* 透明玻璃按钮样式 */
:deep(.el-button) {
  background: rgba(255, 255, 255, 0.05) !important;
  border: 1px solid rgba(255, 255, 255, 0.1) !important;
  color: rgba(255, 255, 255, 0.9) !important;
  backdrop-filter: blur(10px) !important;
  transition: all 0.3s ease !important;
  border-radius: 8px !important;
  font-weight: 500 !important;

  &:hover {
    background: rgba(255, 255, 255, 0.1) !important;
    border-color: rgba(0, 234, 255, 0.3) !important;
    transform: translateY(-1px) !important;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2) !important;
    color: #ffffff !important;
  }

  &.el-button--primary {
    background: linear-gradient(135deg, rgba(0, 234, 255, 0.8), rgba(0, 153, 204, 0.8)) !important;
    border-color: rgba(0, 234, 255, 0.6) !important;
    color: #ffffff !important;
    box-shadow: 0 4px 15px rgba(0, 234, 255, 0.3) !important;

    &:hover {
      background: linear-gradient(135deg, rgba(51, 240, 255, 0.9), rgba(0, 184, 230, 0.9)) !important;
      box-shadow: 0 6px 20px rgba(0, 234, 255, 0.4) !important;
    }
  }

  &.el-button--info {
    background: linear-gradient(135deg, rgba(108, 117, 125, 0.8), rgba(73, 80, 87, 0.8)) !important;
    border-color: rgba(108, 117, 125, 0.6) !important;
    color: #ffffff !important;
    box-shadow: 0 4px 15px rgba(108, 117, 125, 0.3) !important;

    &:hover {
      background: linear-gradient(135deg, rgba(130, 138, 145, 0.9), rgba(90, 98, 104, 0.9)) !important;
      box-shadow: 0 6px 20px rgba(108, 117, 125, 0.4) !important;
    }
  }

  &.el-button--danger {
    background: linear-gradient(135deg, rgba(220, 53, 69, 0.8), rgba(176, 42, 55, 0.8)) !important;
    border-color: rgba(220, 53, 69, 0.6) !important;
    color: #ffffff !important;
    box-shadow: 0 4px 15px rgba(220, 53, 69, 0.3) !important;

    &:hover {
      background: linear-gradient(135deg, rgba(225, 83, 97, 0.9), rgba(190, 60, 75, 0.9)) !important;
      box-shadow: 0 6px 20px rgba(220, 53, 69, 0.4) !important;
    }
  }

  &:disabled {
    background: rgba(255, 255, 255, 0.02) !important;
    border-color: rgba(255, 255, 255, 0.05) !important;
    color: rgba(255, 255, 255, 0.3) !important;
    cursor: not-allowed !important;
    transform: none !important;
    box-shadow: none !important;
  }
}

/* 操作按钮容器样式优化 */
.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: nowrap;
  justify-content: center;
  align-items: center;
  min-width: 270px;
  padding: 4px;
}

.action-btn {
  min-width: 75px !important;
  height: 34px !important;
  padding: 0 12px !important;
  border-radius: 8px !important;
  font-size: 12px !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  transition: all 0.3s ease !important;
  white-space: nowrap !important;
  flex-shrink: 0 !important;

  i {
    font-size: 12px !important;
    margin-right: 4px !important;
  }
}

/* 确保表格操作列有足够的空间且不被遮挡 */
:deep(.el-table .el-table__cell) {
  padding: 8px 4px !important;
  position: relative !important;
}

:deep(.el-table .el-table__cell:has(.action-buttons)) {
  padding: 8px 12px !important;
  overflow: visible !important;
  z-index: 10 !important;
  position: relative !important;
}

/* 优化表格行高 */
:deep(.el-table .el-table__row) {
  height: 50px !important;
  position: relative !important;
}

/* 确保固定列不遮挡按钮 */
:deep(.el-table__fixed-right) {
  z-index: 5 !important;
}

:deep(.el-table__fixed-right .el-table__cell) {
  z-index: 10 !important;
  background: rgba(13, 21, 43, 0.95) !important;
  backdrop-filter: blur(10px) !important;
}

.permissions-management {
  max-height: 600px;
  overflow-y: auto;
  padding: 16px;
  background: rgba(255, 255, 255, 0.01);
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.05);
}

.permissions-section h4 {
  margin: 0 0 20px 0;
  color: #00eaff;
  font-size: 18px;
  font-weight: 600;
  text-shadow: 0 0 10px rgba(0, 234, 255, 0.5);
  padding-bottom: 10px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

/* 权限树样式优化 */
:deep(.permission-tree) {
  background: transparent !important;
  color: #ffffff !important;

  .el-tree-node {
    margin: 4px 0 !important;
  }

  .el-tree-node__content {
    background: transparent !important;
    border-radius: 8px !important;
    margin: 2px 0 !important;
    padding: 12px 16px !important;
    transition: all 0.3s ease !important;
    min-height: 50px !important;
    border: 1px solid transparent !important;

    &:hover {
      background: rgba(255, 255, 255, 0.05) !important;
      border-color: rgba(0, 234, 255, 0.2) !important;
    }
  }

  .el-tree-node__expand-icon {
    color: #00eaff !important;
    font-size: 14px !important;
  }

  .el-checkbox__input.is-checked .el-checkbox__inner {
    background-color: #00eaff !important;
    border-color: #00eaff !important;
  }

  .el-checkbox__inner {
    border-color: rgba(255, 255, 255, 0.3) !important;
    background: rgba(255, 255, 255, 0.05) !important;
    width: 16px !important;
    height: 16px !important;
  }

  .el-checkbox__inner::after {
    border-color: #ffffff !important;
    border-width: 2px !important;
  }
}

/* 权限树节点包装器 */
.tree-node-wrapper {
  width: 100%;
}

/* 菜单节点样式优化 */
.menu-node {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  min-height: 40px;
  padding: 8px 0;
  gap: 16px;
}

.menu-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
  min-width: 0;
}

.menu-icon {
  font-size: 16px;
  color: #00eaff;
  width: 20px;
  text-align: center;
  flex-shrink: 0;
}

.menu-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
  flex: 1;
  min-width: 0;
}

.menu-name {
  font-size: 14px;
  font-weight: 500;
  color: #ffffff;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.menu-path {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.5);
  background: rgba(0, 234, 255, 0.1);
  padding: 2px 6px;
  border-radius: 10px;
  border: 1px solid rgba(0, 234, 255, 0.2);
  font-family: 'Courier New', monospace;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 180px;
  display: inline-block;
}

/* 权限控制内联显示 */
.permission-controls-inline {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-shrink: 0;
  min-width: 280px;
}

.permission-status-tag {
  min-width: 60px !important;
  text-align: center !important;
  font-weight: 500 !important;
  border-radius: 12px !important;
  padding: 4px 12px !important;
  flex-shrink: 0;
}

.permission-button-group {
  display: flex;
  gap: 6px;
  flex-shrink: 0;
}

.permission-control-btn {
  min-width: 70px !important;
  height: 28px !important;
  padding: 0 12px !important;
  border-radius: 6px !important;
  font-size: 11px !important;
  font-weight: 500 !important;
  transition: all 0.3s ease !important;
  background: rgba(255, 255, 255, 0.05) !important;
  border: 1px solid rgba(255, 255, 255, 0.1) !important;
  color: rgba(255, 255, 255, 0.9) !important;
  backdrop-filter: blur(10px) !important;

  i {
    margin-right: 4px !important;
    font-size: 10px !important;
  }

  &:hover {
    background: rgba(255, 255, 255, 0.1) !important;
    border-color: rgba(0, 234, 255, 0.3) !important;
    transform: translateY(-1px) !important;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2) !important;
    color: #ffffff !important;
  }

  &.el-button--primary {
    background: linear-gradient(135deg, rgba(0, 234, 255, 0.8), rgba(0, 153, 204, 0.8)) !important;
    border-color: rgba(0, 234, 255, 0.6) !important;
    color: #ffffff !important;
    box-shadow: 0 4px 15px rgba(0, 234, 255, 0.3) !important;

    &:hover {
      background: linear-gradient(135deg, rgba(51, 240, 255, 0.9), rgba(0, 184, 230, 0.9)) !important;
      box-shadow: 0 6px 20px rgba(0, 234, 255, 0.4) !important;
    }
  }

  &.active-permission {
    box-shadow: 0 0 15px rgba(0, 234, 255, 0.6) !important;
    transform: translateY(-1px) !important;
  }
}

.text-muted {
  color: rgba(255, 255, 255, 0.5);
}

.group-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 2px;
  align-items: center;
}

.group-detail {
  padding: 8px;
}

.group-detail h4 {
  font-size: 14px;
  font-weight: 600;
}

.group-list {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

/* 透明玻璃弹窗样式 */
:deep(.el-dialog) {
  background: rgba(255, 255, 255, 0.02) !important;
  border: 1px solid rgba(255, 255, 255, 0.08) !important;
  backdrop-filter: blur(20px) saturate(150%) !important;
  border-radius: 16px !important;
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.1) !important;

  .el-dialog__header {
    background: transparent !important;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1) !important;
    padding: 20px 24px 16px 24px !important;

    .el-dialog__title {
      color: #ffffff !important;
      font-size: 18px !important;
      font-weight: 600 !important;
      text-shadow: 0 0 10px rgba(255, 255, 255, 0.3) !important;
    }

    .el-dialog__headerbtn {
      .el-dialog__close {
        color: rgba(255, 255, 255, 0.7) !important;
        font-size: 18px !important;

        &:hover {
          color: #ff4757 !important;
        }
      }
    }
  }

  .el-dialog__body {
    background: transparent !important;
    padding: 24px !important;
    color: #ffffff !important;
  }

  .el-dialog__footer {
    background: transparent !important;
    border-top: 1px solid rgba(255, 255, 255, 0.1) !important;
    padding: 16px 24px 20px 24px !important;
  }
}

/* 表单样式优化 */
:deep(.el-form-item__label) {
  color: rgba(255, 255, 255, 0.9) !important;
  font-weight: 500 !important;
}

:deep(.el-input) {
  .el-input__wrapper {
    background: rgba(255, 255, 255, 0.05) !important;
    border: 1px solid rgba(255, 255, 255, 0.1) !important;
    backdrop-filter: blur(10px) !important;
    border-radius: 8px !important;

    &:hover {
      border-color: rgba(0, 234, 255, 0.3) !important;
    }

    &.is-focus {
      border-color: rgba(0, 234, 255, 0.6) !important;
      box-shadow: 0 0 0 2px rgba(0, 234, 255, 0.2) !important;
    }

    .el-input__inner {
      color: #ffffff !important;
      background: transparent !important;

      &::placeholder {
        color: rgba(255, 255, 255, 0.5) !important;
      }
    }
  }
}

/* 用户组容器样式 */
.groups-container {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  cursor: pointer;
  padding: 2px 4px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.groups-container:hover {
  background: rgba(164, 244, 186, 0.1);
  transform: translateY(-1px);
}

.single-groups {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
}
</style>
